package com.hljcj.boot.service;

import com.hljcj.boot.bean.SysPost;
import com.hljcj.boot.dao.PostDao;
import com.hljcj.boot.dao.PostRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

@Service
public class PostService {

    @Resource
    private PostRepository postRepository;
    
    @Resource
    private PostDao postDao;

    public Page<SysPost> queryPost(int pageNo, int pageSize) {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        Page<SysPost> posts = postRepository.findAll(pageable);
        return posts;
    }

    public Page<SysPost> queryPost(SysPost sysPost, int pageNo, int pageSize) throws Exception {
        Page<SysPost> page = postDao.queryPost(sysPost, pageNo, pageSize);
        return page;
    }

    @Transactional
    public String addPost(SysPost post) {
        List<SysPost> tmp = postRepository.findByPostName(post.getPostName());
        if (null == tmp || tmp.size() == 0) {
            postRepository.save(post);
            return "succ";
        } else {
            return "部门名称：" + post.getPostName() + "，重复，保存失败！";
        }
    }

    @Transactional
    public String updPost(SysPost post) {
        List<SysPost> ls = postRepository.findByPostName(post.getPostName());
        if (null != ls && ls.size() > 0) {
            SysPost temp = ls.get(0);
            if (temp.getPostId() == post.getPostId()) {
                postRepository.save(post);
                return "succ";
            } else {
                return "部门名称：" + post.getPostName() + "，重复，保存失败！";
            }
        } else {
            postRepository.save(post);
            return "succ";
        }
    }

    /**
     * 删除一个部门
     *
     * @param postId
     */
    @Transactional
    public void delPost(Integer postId) {
        postRepository.deleteById(postId);
    }
}
